// utils/searchHistory.ts
import preferences from '@ohos.data.preferences';

const MAX_HISTORY_ITEMS = 10;
const HISTORY_KEY = 'search_history';

class SearchHistory {
  private historyItems: string[] = [];

  async initialize(context: any) {
    try {
      const pref = await preferences.getPreferences(context, 'app_preferences');
      const savedHistory = await pref.get(HISTORY_KEY, '[]');
      this.historyItems = JSON.parse(String(savedHistory));
    } catch (error) {
      console.error('Failed to load search history:', error);
    }
  }

  async addItem(item: string, context: any) {
    // 移除重复项
    this.historyItems = this.historyItems.filter(i => i !== item);
    // 添加到开头
    this.historyItems.unshift(item);
    // 限制数量
    if (this.historyItems.length > MAX_HISTORY_ITEMS) {
      this.historyItems = this.historyItems.slice(0, MAX_HISTORY_ITEMS);
    }

    await this.save(context);
  }

  async removeItem(item: string, context: any) {
    this.historyItems = this.historyItems.filter(i => i !== item);
    await this.save(context);
  }

  async clear(context: any) {
    this.historyItems = [];
    await this.save(context);
  }

  getItems(): string[] {
    return [...this.historyItems];
  }

  private async save(context: any) {
    try {
      const pref = await preferences.getPreferences(context, 'app_preferences');
      await pref.put(HISTORY_KEY, JSON.stringify(this.historyItems));
      await pref.flush();
    } catch (error) {
      console.error('Failed to save search history:', error);
    }
  }
}

export const searchHistory = new SearchHistory();